package com.mayikt.edu.service.impl;

import com.mayikt.edu.constant.MayiktConstants;
import com.mayikt.edu.domain.EduUser;
import com.mayikt.edu.dto.req.RegisterReqDTO;
import com.mayikt.edu.mapper.EduUserMapper;
import com.mayikt.edu.service.EduUserService;
import com.mayikt.edu.service.RegisterService;
import com.mayikt.edu.utils.MD5Utils;
import com.mayikt.edu.utils.SaltUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wangjin
 * @date 2023年10月30日 9:32
 */
@Slf4j
@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private EduUserService eduUserService;
    @Autowired
    private EduUserMapper eduUserMapper;

    @Override
    public boolean register(RegisterReqDTO registerReqDTO) {
        // 1.验证码参数
        String userName = registerReqDTO.getUserName();
        if (StringUtils.isEmpty(userName)) {
            log.error("[userName is null]");
            return Boolean.FALSE;
        }
        // 根据名称从db查找到用户信息
        EduUser dbEduUser = eduUserService.findByUserNameEduUser(userName);
        if (dbEduUser != null) {
            log.error("[从数据库中查找到数据:{},无需重复注册]", registerReqDTO);
            return Boolean.FALSE;
        }
        String password = registerReqDTO.getPassword();
        if (StringUtils.isEmpty(password)) {
            log.error("[password is null]");
            return Boolean.FALSE;
        }
        //用户密码+盐值
        String salt = SaltUtils.getSalt();
        String newPassword = MD5Utils.md5(password + salt);
        EduUser eduUser = new EduUser();
        eduUser.setUserName(userName);
        eduUser.setPassword(newPassword);
        eduUser.setUserSalt(salt);
        return eduUserMapper.insert(eduUser) > MayiktConstants.DB_INSERT_RESULT_BIGZERO;
    }
}
